﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using LiveEduWizard.Views;

namespace LiveEduWizard
{
    public partial class TimetableItem : UserControl
    {
        private Timetable.TimeRange range;
        private int rowHeight;

        public TimetableItem()
            : this(null, new Timetable.TimeRange(7,19), 90)
        {            
        }

        public TimetableItem(AppointmentViewModel appointment, Timetable.TimeRange range, int rowHeight)
        {
            this.range = range;
            this.rowHeight = rowHeight;

            InitializeComponent();

            Appointment = appointment;
        }

        private AppointmentViewModel appointment = null;
        public AppointmentViewModel Appointment 
        {
            get { return appointment; }
            set
            {
                if (appointment != value)
                {
                    this.appointment = value;
                    DataContext = appointment;
                    UpdatePosition();
                }
            }
        }

        public void UpdatePosition()
        {
            if (appointment == null 
                || appointment.Start.Date == appointment.End.Date && appointment.End.Hour < range.Start 
                || appointment.Start.Hour > range.End)
                Visibility = Visibility.Collapsed;
            else
            {
                Visibility = Visibility.Visible;

                DateTime start = appointment.Start.Hour >= range.Start ? appointment.Start : 
                    new DateTime(appointment.Start.Year, appointment.Start.Month, appointment.Start.Day, range.Start, 0, 0);
                DateTime end = start.Date == appointment.End.Date && appointment.End.Hour <= range.End ? appointment.End :
                    new DateTime(start.Year, start.Month, start.Day, range.End, 59, 59, 99);

                Height = (end - start).TotalHours * rowHeight;
                Margin = new Thickness(5, rowHeight * (start.Minute) / 60.0, 5, 0);

                Grid.SetRow(this, start.Hour - range.Start);
            }
        }

        public void UpdatePosition(Timetable.TimeRange range, int rowHeight)
        {
            this.range = range;
            this.rowHeight = rowHeight;

            UpdatePosition();
        }

        private void UserControl_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AppointmentView.Show(appointment);            
        }        
    }
}
